/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.job.task;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import io.renren.common.utils.DateUtils;
import io.renren.modules.alarmcallrel.service.AlarmCallRelService;
import io.renren.modules.call.service.CallService;
import io.renren.modules.device.entity.vo.DeviceThresholdVO;
import io.renren.modules.device.service.TDeviceThresholdService;
import io.renren.modules.monitor.entity.vo.MonitorAlarmVO;
import io.renren.modules.monitor.service.MonitorAlarmService;
import io.renren.modules.alarmcallrel.entity.AlarmCallRelEntity;

/**
 * 测试定时任务(演示Demo，可删除)
 *
 * testTask为spring bean的名称
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component("alarmTask")
public class AlarmTask implements ITask {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private TDeviceThresholdService tDeviceThresholdService;
	@Autowired
	private MonitorAlarmService monitorAlarmService;
	@Autowired
	private AlarmCallRelService alarmCallRelService;
	@Autowired
	private CallService callService;
	
	@Override
	public void run(String params){
		logger.debug("AlarmTask定时任务正在执行，参数为：{}", params);
		String startTime = DateUtils.format(new Date(), DateUtils.DATE_PATTERN) + "00:00:00";
		String endTime = DateUtils.format(new Date(), DateUtils.DATE_PATTERN) + "23:59:59";
		// 按照时间查找告警信息
		List<MonitorAlarmVO> alarms = monitorAlarmService.queryMonitorAlarmsByEventTime(startTime, endTime);
		if(CollectionUtils.isNotEmpty(alarms)) {
			// 如果找到告警信息，则按照报警类型和设备类型匹配告警配置
			alarms.stream().forEach(al->{
				int alarmTypeID =   al.getEventId();
				String deviceCategoryID = al.getType();
				List<DeviceThresholdVO> result = tDeviceThresholdService.getDeviceThresholdInfoByDeviceCategoryIdAndAlarmTypeId(Long.parseLong(deviceCategoryID), new Long(alarmTypeID));
				if(CollectionUtils.isNotEmpty(result)) {
					result.forEach(info->{ // 查询告警配置-呼叫配置关联表,告警发生时, 需要呼叫的所有号码
						Map<String, Object> param = new HashMap<String, Object>();
						param.put("devicethreshold_id", info.getId());
						List<AlarmCallRelEntity> calls = alarmCallRelService.listByMap(param);
						if(CollectionUtils.isNotEmpty(calls)) {  
							calls.stream().forEach(c->{
								callService.call(c.getId());
							});
							
						}
						
					});

				}
			});
		}
		
	}
}
